package com.sudo.common.utils;

import com.sudo.common.constant.UserConstant;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Map;

/**
 * @Author：DayDayUp
 * @Create：2023/2/7 9:48
 */
public class HttpUserInfoUtil {
    private HttpUserInfoUtil(){}

    public static final String[] needUserInfoUri = {"/fileRun/uploadMyLogo"};

    private static String getCookie(HttpServletRequest request){
        return CookieUtil.getCookieValue(request, UserConstant.COOKIE_NAME, true);
    }

    /**
     * 目前只有在上传用户logo的时候用到，因为表单不能提交cookie
     */
    private static String getUserInfo(HttpServletRequest request){
        String userInfo = null;
        try {
            userInfo = URLDecoder.decode(request.getHeader("userInfo"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return userInfo;
    }

    private static Map<String, String> getCookieMap(HttpServletRequest request){
        String userInfo = getCookie(request);
        if (StringUtils.isBlank(userInfo) && Arrays.asList(needUserInfoUri).contains(request.getRequestURI())) {
            userInfo = getUserInfo(request);
        }
        if (StringUtils.isBlank(userInfo)){
            return null;
        }
        return JsonUtil.jsonToPojo(userInfo, Map.class);
    }

    public static String getSessionUser(HttpServletRequest request) {
        Map<String, String> cookieMap = getCookieMap(request);
        return cookieMap == null?null:cookieMap.get(UserConstant.COOKIE_USER_NAME);
    }

    public static String getSessionToken(HttpServletRequest request) {
        Map<String, String> cookieMap = getCookieMap(request);
        return cookieMap == null?null:cookieMap.get(UserConstant.COOKIE_UNIQUE_TOKEN);
    }

}
